package app.itgungnir.compose.wan.business.main.mine

import android.content.res.Configuration
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Card
import androidx.compose.material.Icon
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.*
import androidx.compose.material.icons.outlined.Face
import androidx.compose.material.icons.outlined.NoAccounts
import androidx.compose.runtime.Composable
import androidx.compose.runtime.State
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.navigation.NavController
import androidx.navigation.compose.rememberNavController
import app.itgungnir.compose.wan.CoinInfo
import app.itgungnir.compose.wan.Routes
import app.itgungnir.compose.wan.UserInfo
import app.itgungnir.compose.wan.theme.MineBackgroundShape
import app.itgungnir.compose.wan.theme.WanComposePreviewTheme
import app.itgungnir.compose.wan.utils.LocalDataStore
import app.itgungnir.compose.wan.widgets.WanBadge
import app.itgungnir.compose.wan.widgets.WanDescription
import app.itgungnir.compose.wan.widgets.WanDivider
import app.itgungnir.compose.wan.widgets.WanHeader

@Composable
fun MineUI(
    navController: NavController = rememberNavController(),
    hasLoginState: State<Boolean> = mutableStateOf(false),
    userInfoState: State<UserInfo?> = mutableStateOf(null),
    coinInfoState: State<CoinInfo?> = mutableStateOf(null),
    onLogout: () -> Unit = {},
    unreadMsgCount: Int = 0
) {
    Box(
        modifier = Modifier
            .fillMaxSize()
            .background(MaterialTheme.colors.surface)
            .background(MaterialTheme.colors.primary, MineBackgroundShape())
    ) {
        LazyColumn(modifier = Modifier.fillMaxWidth()) {
            item { UserBaseInfo(navController = navController, userInfoState = userInfoState) }
            item { UserCoinInfo(navController = navController, coinInfoState = coinInfoState) }
            item { UserSettings(navController = navController, unreadMsgCount = unreadMsgCount) }
            item { SystemSettings(navController = navController) }
            item { UserLogout(hasLoginState = hasLoginState, onLogout = onLogout) }
        }
    }
}

@Composable
private fun UserBaseInfo(navController: NavController = rememberNavController(), userInfoState: State<UserInfo?>) {
    val interactionSource = remember { MutableInteractionSource() }
    val userInfo = userInfoState.value
    Column(
        modifier = Modifier
            .fillMaxWidth()
            .clickable(interactionSource = interactionSource, indication = null) {
                navigate(navController = navController, needLogin = true)
            },
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        Spacer(modifier = Modifier.height(50.dp))
        Box(
            modifier = Modifier
                .size(120.dp)
                .clip(RoundedCornerShape(75.dp))
                .background(MaterialTheme.colors.background)
        ) {
            Icon(
                modifier = Modifier.fillMaxSize(),
                imageVector = when (userInfo?.name.isNullOrEmpty()) {
                    true -> Icons.Outlined.NoAccounts
                    else -> Icons.Outlined.Face
                },
                contentDescription = "",
                tint = MaterialTheme.colors.primary
            )
        }
        Spacer(modifier = Modifier.height(10.dp))
        WanHeader(
            content = userInfo?.name?.takeIf { it.isNotEmpty() } ?: "点我登录",
            color = MaterialTheme.colors.onPrimary
        )
        userInfo?.id?.takeIf { it > 0L }?.let { userId ->
            WanDescription(content = "id: $userId", color = MaterialTheme.colors.onPrimary)
        }
    }
}

@Composable
private fun UserCoinInfo(navController: NavController = rememberNavController(), coinInfoState: State<CoinInfo?>) {
    val coinInfo = coinInfoState.value
    Card(
        modifier = Modifier
            .fillMaxWidth()
            .padding(start = 25.dp, end = 25.dp, top = 35.dp, bottom = 20.dp),
        elevation = 5.dp,
        shape = RoundedCornerShape(12.dp)
    ) {
        Column {
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .background(MaterialTheme.colors.background)
                    .clickable {
                        navigate(navController = navController, route = Routes.COIN_MANIFEST, needLogin = true)
                    }
                    .padding(top = 20.dp, bottom = 20.dp),
                horizontalArrangement = Arrangement.SpaceEvenly,
                verticalAlignment = Alignment.CenterVertically
            ) {
                CoinItem("等级", coinInfo?.level?.takeIf { it > 0 }?.toString() ?: "--")
                WanDivider(width = 1.dp, height = 35.dp)
                CoinItem("积分", coinInfo?.coins?.takeIf { it > 0 }?.toString() ?: "--")
                WanDivider(width = 1.dp, height = 35.dp)
                CoinItem("排名", coinInfo?.rank?.takeIf { it.isNotEmpty() } ?: "--")
            }
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .background(MaterialTheme.colors.primary.copy(alpha = 0.4F))
                    .clickable {
                        navigate(navController = navController, route = Routes.COIN_RANK)
                    }
                    .padding(vertical = 10.dp),
                horizontalArrangement = Arrangement.Center,
                verticalAlignment = Alignment.CenterVertically
            ) {
                WanDescription(content = "查看全部排名", color = MaterialTheme.colors.onPrimary)
                Icon(
                    imageVector = Icons.Filled.ChevronRight,
                    contentDescription = "",
                    tint = MaterialTheme.colors.onPrimary
                )
            }
        }
    }
}

@Composable
private fun CoinItem(title: String, value: String) {
    Column(horizontalAlignment = Alignment.CenterHorizontally) {
        Text(text = title, style = MaterialTheme.typography.body1, color = MaterialTheme.colors.primary)
        Text(text = value, style = MaterialTheme.typography.h6, color = MaterialTheme.colors.primary)
    }
}

@Composable
private fun UserSettings(navController: NavController = rememberNavController(), unreadMsgCount: Int = 0) {
    Card(
        modifier = Modifier
            .fillMaxWidth()
            .padding(start = 25.dp, end = 25.dp, bottom = 25.dp),
        elevation = 4.dp,
        shape = RoundedCornerShape(12.dp),
        backgroundColor = MaterialTheme.colors.background
    ) {
        Column(modifier = Modifier.fillMaxWidth()) {
            SettingItem(icon = Icons.Filled.Favorite, title = "我喜欢的文章") {
                navigate(navController = navController, route = Routes.MY_COLLECTIONS, needLogin = true)
            }
            WanDivider(modifier = Modifier.padding(horizontal = 15.dp), fillWidth = true, height = 1.dp)
            SettingItem(icon = Icons.Filled.Category, title = "我常用的网站") {
                navigate(navController = navController, route = Routes.MY_WEBSITES, needLogin = true)
            }
            WanDivider(modifier = Modifier.padding(horizontal = 15.dp), fillWidth = true, height = 1.dp)
            SettingItem(
                icon = Icons.Filled.Notifications,
                title = "站内消息",
                badgeText = unreadMsgCount.takeIf { it > 0 }?.run { "$this" }
            ) {
                navigate(navController = navController, route = Routes.MESSAGE, needLogin = true)
            }
        }
    }
}

@Composable
private fun SystemSettings(navController: NavController = rememberNavController()) {
    Card(
        modifier = Modifier
            .fillMaxWidth()
            .padding(start = 25.dp, end = 25.dp, bottom = 25.dp),
        elevation = 4.dp,
        shape = RoundedCornerShape(12.dp),
        backgroundColor = MaterialTheme.colors.background
    ) {
        Column(modifier = Modifier.fillMaxWidth()) {
            SettingItem(icon = Icons.Filled.Info, title = "关于我们") {
                navigate(navController = navController, route = Routes.SETTINGS)
            }
            WanDivider(modifier = Modifier.padding(horizontal = 15.dp), fillWidth = true, height = 1.dp)
            SettingItem(icon = Icons.Filled.Settings, title = "系统设置") {
                navigate(navController = navController, route = Routes.SETTINGS)
            }
        }
    }
}

@Composable
private fun UserLogout(hasLoginState: State<Boolean>, onLogout: () -> Unit) {
    if (hasLoginState.value) {
        Card(
            modifier = Modifier
                .fillMaxWidth()
                .padding(start = 25.dp, end = 25.dp, bottom = 25.dp),
            elevation = 4.dp,
            shape = RoundedCornerShape(12.dp),
            backgroundColor = MaterialTheme.colors.background
        ) {
            WanDescription(
                modifier = Modifier
                    .fillMaxWidth()
                    .clickable { onLogout.invoke() }
                    .padding(vertical = 15.dp),
                content = "退出登录",
                color = MaterialTheme.colors.error,
                textAlign = TextAlign.Center
            )
        }
    }
}

@Composable
private fun SettingItem(icon: ImageVector, title: String, badgeText: String? = null, onClick: () -> Unit) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .clickable { onClick.invoke() }
            .padding(horizontal = 15.dp),
        verticalAlignment = Alignment.CenterVertically
    ) {
        Icon(imageVector = icon, contentDescription = "", tint = MaterialTheme.colors.primary)
        WanDescription(modifier = Modifier.padding(start = 15.dp, top = 20.dp, bottom = 20.dp), content = title)
        Spacer(modifier = Modifier.weight(1F, fill = true))
        badgeText?.takeIf { it.isNotEmpty() }?.let {
            WanBadge(badgeContent = { Text(text = it) }) {}
        }
        Icon(
            modifier = Modifier.padding(start = 10.dp),
            imageVector = Icons.Filled.ChevronRight,
            contentDescription = ""
        )
    }
}

private fun navigate(
    navController: NavController,
    route: String? = null,
    needLogin: Boolean = false
) {
    if (needLogin && !LocalDataStore.localData.hasLogin) {
        navController.navigate(Routes.LOGIN)
    } else {
        route?.takeIf { it.isNotEmpty() }?.let { navController.navigate(it) }
    }
}

@Preview(name = "Light mode")
@Preview(name = "Dark mode", uiMode = Configuration.UI_MODE_NIGHT_YES, showBackground = true)
@Composable
private fun MinePreview() {
    WanComposePreviewTheme {
        MineUI()
    }
}
